<template>
	<div class="choose-list-top" ref="aff">
		<template v-if="!isSearch">
			<div class="choose-list-top-count">
				<span v-if="isSingle" class="choose-list-top-one">{{ $i18n('selectPeople.options.one.lable') }}</span>
				<span v-else  class="choose-list-top-one">{{$i18n('selectPeople.selected', this.selectedList.length)}}</span>
				<span class="clear-btn" @click.stop="onClear" v-show="selectedList.length">{{ $i18n('common.button.clear.label') }}</span>
				<div
					class="choose-list-top-btns-save"
					@click="visible = true"
					v-show="!showAddEdocAddAccount && !showAddEdocOrgTeam && onlyMember && !hiddenSaveAsTeam"
				>
					<span class="choose-list-top-btns-save-label"> {{$i18n('selectPeople.saveAsTeam.lable')}} </span>
				</div>
				<addAccountDialog
					v-show="showAddEdocAddAccount"
					@toUpdateAccountList="onUpdateAccountList"
				/>
				<addEdocOrgTeamDialog
					v-show="showAddEdocOrgTeam"
					@onUpdateEdocOrgTeamList="onUpdateEdocOrgTeamList"
				/>
			</div>
			<div class="choose-list-top-btns">
				<div
					class="choose-list-top-btns-search"
					v-if="!isSingle"
					@click="openSearch"
				>
					<a-icon type="search" />
				</div>
				<div class="is-avter">
					<a-checkbox :checked="isShowAvator" @change="onChangeLabel">
						<span class="label-text">{{ $i18n('selectPeople.image') }}</span>
					</a-checkbox>
				</div>

			</div>
		</template>
		<template v-else>
			<a-input-search
				class="choose-list-top-input"
				:placeholder="$i18n('form.binddesign.conditionstyle.combox.placeholder')"
				v-model.trim="search"
				@pressEnter="toSearch"
				@change="onInputChange"
			>
				<span slot="suffix">
					<icon-font @click.stop="onClearSearch" v-show="search" type="cap-icon-guanbi" class="input-clear-icon"/>
					<span @click.stop="closeSearch" class="input-clear-btn">{{$i18n('common.button.cancel.label')}}</span>
				</span>

				<a-button slot="enterButton" class="last-button-box button-hover-box" @click.stop="toSearch">
					<a-icon type="search" />
				</a-button>
			</a-input-search>
		</template>
		<a-modal
			:visible="visible"
			:cancelText="$i18n('common.button.cancel.label')"
			:okText="$i18n('common.button.ok.label')"
			:title="$i18n('selectPeople.saveAsTeam.lable')"
			:confirmLoading="confirmLoading"
			:maskClosable="false"
			:dialog-style="{ top: '200px' }"
			@ok="handleOk"
			@cancel="handleCancel"
			:global="dialogWindow"
		>
			<a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
				<a-form-item :label="$i18n('selectPeople.teamName')" class="a-form-item-box">
					<a-input
						:placeholder="$i18n('selectPeople.input',$i18n('org.team.label'))"
						v-decorator="[
							'name',
							{
								rules: [
									{ required: true, message: $i18n('selectPeople.input.team.name')},
									{
										pattern: /^[\u4E00-\u9FA5A-Za-z0-9-+=]{1,120}$/,
										message: $i18n('selectPeople.team.char.not'),
									},
								],
							},
						]"
					/>
				</a-form-item>
				<a-form-item :label="$i18n('selectPeople.TeamMember_label')" class="a-form-item-box last-form-item">
					<a-textarea
						v-decorator="['group']"
						autoSize
						disabled
						style="resize: none; height: 156px"
					/>
				</a-form-item>
			</a-form>
		</a-modal>
		<a-modal
			:visible="isExist"
			:cancelText="$i18n('common.button.cancel.label')"
			:okText="$i18n('common.button.ok.label')"
			:title="$i18n('common.system.hint.label')"
			:confirmLoading="confirmLoading"
			:maskClosable="false"
			:dialog-style="{ top: '0px' }"
			@ok="confirmHandler"
			@cancel="cancelHandler"
			:global="dialogWindow"
			:getContainer="()=>$refs.aff"
		>
			<div class="modal-content">
				<div class="check-title-box">
					<p class="title-item">{{ $i18n('common.organization.recover') }}</p>
				</div>
			</div>
		</a-modal>
	</div>
</template>

<script>
import { getPanelData } from '@/api/modules/SelectOrgApi';
import { mapActions, mapGetters, mapState } from 'vuex';
import { entityFormat } from '@/utils/utils';
import { ACTION_REMOVE_ENTITY } from '@/store/actionTypes';
import addAccountDialog from './addAccountDialog.vue';
import addEdocOrgTeamDialog from './addEdocOrgTeamDialog.vue';
import { EntityTypes, GroupId } from '@/utils/orgConstants';

export default {
	props: {
		checked: { type: Object, default: {} }
	},
	inject: ['app'],
	components: { addAccountDialog, addEdocOrgTeamDialog },
	data() {
		return {
			isExist: false,
			isSearch: false,
			search: '',
			visible: false,
			confirmLoading: false,
			form: this.$form.createForm(this)

		};
	},
	computed: {
		...mapGetters('selectData',['isSingle']),
		...mapState('selectData', ['selectedList']),
		hiddenSaveAsTeam() {
			return this.app().orgSelect.hiddenSaveAsTeam;
		},
		isShowAvator() {
			return this.app().isShowAvator;
		},
		onlyMember() {
			let selectedList = this.selectedList;
			if (selectedList.length > 1) {
				return selectedList.every((item) => item.type === 'Member');
			} else {
				return false;
			}
		},
		showAddEdocOrgTeam() {
			return this.app().activeTab === 'OrgTeam' && this.onlyUnit;
		},
		showAddEdocAddAccount() {
			return this.app().activeTab === 'ExchangeAccount';
		},
		onlyUnit() {
			let selectedList = this.selectedList;
			if (selectedList.length >= 1) {
				// 选择集团也不能
				return selectedList.every((item) => item.type === EntityTypes.Department
					|| (item.type === EntityTypes.Account && item.id !== GroupId) || item.type === EntityTypes.OrgMetadataTag);
			} else {
				return false;
			}
		},
		selectFormatList() {
			const orgSelect = this.app().orgSelect;
			const { loginAccountId } = orgSelect;
			return this.selectedList.map(entity => {
				const dataFormat = entityFormat(entity, loginAccountId, orgSelect);
				entity.label = dataFormat.name;
				return entity;
			});
		}

	},
	watch: {
		visible(val) {
			if (val) {
				window.showbarMask();
			} else {
				window.hidebarMask();
			}
			this.confirmLoading = false;
			if (!val) {
				return;
			}
			this.$nextTick(() => {
				this.form.setFieldsValue({
					name: '',
					group: this.selectedList.map((it) => it.name).join(',')
				});
			});
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_REMOVE_ENTITY]),
		toSearch() {
			if (this.search === '') {
				this.$emit('toSearchCallBack', []);
				return;
			}
			const searchResult = [];
			this.selectFormatList.forEach((it) => {
				const label = it.label.toLowerCase();
				if (label.includes(this.search.toLowerCase())) {
					searchResult.push(it);
				}
			});
			this.$emit('toSearchCallBack', searchResult);
		},
		onUpdateEdocOrgTeamList() {
			// 添加外部单位，通过 edocOrgTeamPanel，更新外部单位数据
			this.$root.$emit('AddEdocOrgTeam');
		},
		onUpdateAccountList() {
			// 添加外部单位，通过 edocExchangeAccountPanel，更新外部单位数据
			this.$root.$emit('AddEdocAddAccountEvent');
		},
		handleOk() {
			this.form.validateFields((err, values) => {
				if (err) {
					return;
				}
				this.confirmLoading = true;
				getPanelData({
					panel: 'Team',
					command: 'checkNameRepeat',
					arguments: {
						name: values.name
					}
				}).then((res) => {
					if (!res.data) {
						this.isExist = true;
					} else {
						this.saveAsTeam();
					}
				})['finally'](() => {
					this.confirmLoading = false;
				});
			});
		},
		saveAsTeam() {
			const _t = this;
			this.form.validateFields((err, values) => {
				if (err) {
					return;
				}
				this.confirmLoading = true;
				getPanelData({
					panel: 'Team',
					command: 'saveAsTeam',

					arguments: {
						name: values.name,
						memberIds: this.selectedList.map((it) => it.id).join(',')
					}
				}).then((res) => {
					if (res.code === 0) {
						this.$message.success(this.$i18n('common.successfully.saved.label'));
						this.visible = false;
						// 添加外部单位，通过 orgTeamPanel，更新组数据
						_t.$root.$emit('AddTeamEvent');
					} else {
						this.$message.error(res.message);
					}
				})['finally'](() => {
					this.isExist = false;
					this.confirmLoading = false;
				});
			});
		},
		confirmHandler() {
			this.saveAsTeam();
		},
		cancelHandler() {
			this.isExist = false;
		},
		handleCancel() {
			if (this.confirmLoading === true) {
				return;
			}
			this.visible = false;
		},
		closeSearch() {
			this.isSearch = false;
			this.search = '';
			this.$emit('toSearchCallBack', []);
		},
		openSearch() {
			this.isSearch = true;
			this.$nextTick(() => {
				document.querySelector('.choose-list-top-input input').focus();
			});
		},
		onInputChange(e) {
			let value = e.target.value;
			if (!value) {
				this.$emit('toSearchCallBack', []);
			} else {
				this.toSearch();
			}
		},
		onClearSearch() {
			this.search = '';
			this.$emit('toSearchCallBack', []);
		},
		onChangeLabel(val) {
			let check = val.target.checked;
			this.app().onSwitchAvator(check);
		},
		onClear() {
			if (this.selectedList.length) {
				this[ACTION_REMOVE_ENTITY]({
					entities: this.selectedList
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.choose-list-top {
	height: 100%;
	align-items: center;

	.choose-list-top-count {
		float: left;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		color: #333333;
		padding: 0 0 0 14px;

		&>div,&>span{
			float: left;
			height: 31px;
			line-height: 32px;
		}

		.choose-list-top-one {
			color: $postDefalutFontColor
		}
		.choose-list-top-btns-save {
			margin-left: 14px;
			cursor: pointer;
			color: $postDefalutFontColor;

			&:hover {
				color: #1f85ec;
			}
			&::before{
				content: '';
				display: inline-block;
				width: 1px;
				height: 14px;
				background: $borderColor;
				margin: 9px 14px 0 0;
				float: left;
			}
			@include clearFix();
			& .choose-list-top-btns-save-label {
				height: 31px;
				line-height: 31px;
			}
		}

		.clear-btn {
			margin-left: 14px;
			cursor: pointer;
			color: $postDefalutFontColor;
			&:hover {
				color: #1f85ec;
			}
		}
	}

	.choose-list-top-btns {
		float: right;

		&>div{
			float: right;
		}
		.is-avter{
			padding-top: 5px;
			box-sizing: border-box;
		}

		.choose-list-top-btns-search {
			cursor: pointer;
			border-left: 1px solid $borderColor;
			box-sizing: border-box;
			height: 31px;
			width: 32px;
			line-height: 32px;
			text-align: center;
			& i{
				color: rgba(0,0,0,0.45);
				&:hover {
					color: rgba(0,0,0,0.65);
				}
			}
		}

		.ant-checkbox-wrapper .label-text{
			color: $postDefalutFontColor
		}
	}

	.choose-list-top-input {
		& /deep/ .ant-input {
			border: 0;
			height: 31px
		}
		& /deep/ .ant-input:focus,
		& /deep/ .ant-input:hover,
		& /deep/ .ant-input:active {
			border: 0;
			box-shadow: none;
		}
		.last-button-box {
			border-width: 0 0 0 1px!important;
			border-radius: 0;
			width: 32px;
			height: 31px;
			line-height: 32px;
			padding: 0;
			& i {
				color: rgba(0,0,0,0.45);
			}
			&:hover i{
				color: rgba(0,0,0,0.65);
			}
			&:hover,
			&:active,
			&:focus{
				border-width: 0 0 0 1px!important;
				border-color: $borderColor!important;
				border-radius: 0;
				box-shadow:none!important;
			}
		}
		.last-button-box:after,
		.last-button-box::after{
			box-shadow:none!important;
			animation:none!important;
		}
		.input-clear-icon {
			cursor: pointer;
			color: $postDefalutFontColor;
			font-size: 14px
		}
		.input-clear-btn {
			cursor: pointer;
			color: $postDefalutFontColor;
			margin-left:10px;
		}
	}

	/deep/ {
		.ant-input-suffix {
			margin-left: 10px;
			height: 22px;
		}

		.ant-input {
			padding-right: 0 !important;
		}
	}

	.button-hover-box:hover {
		border: 1px solid $borderColor;
		border-right: 0;
	}
}
</style>
